<template>
  <div class="archive-confidentiality-access-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>档案密级与访问控制</span>
        <div style="float: right;">
          <el-button 
            v-if="elasticsearchStatus" 
            type="success" 
            size="mini" 
            @click="syncToElasticsearch"
            :loading="syncLoading">
            <i class="el-icon-refresh"></i>
            同步数据
          </el-button>
        </div>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="输入标题、类型、位置或内容关键词"
              clearable
              @keyup.enter.native="handleSearch"
              style="width: 300px;">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-switch
              v-model="useElasticsearch"
              active-text="智能搜索"
              inactive-text="普通搜索"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleSearchModeChange">
            </el-switch>
          </el-form-item>
          <el-form-item v-if="useElasticsearch">
            <el-tag type="success" size="mini">
              <i class="el-icon-lightning"></i>
              全文搜索已启用
            </el-tag>
          </el-form-item>
          <el-form-item v-if="!elasticsearchStatus">
            <el-tag type="warning" size="mini">
              <i class="el-icon-warning"></i>
              Elasticsearch未连接
            </el-tag>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="archives" style="width: 100%" v-loading="loading">
        <el-table-column prop="archiveId" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="档案标题"></el-table-column>
        <el-table-column prop="archiveType" label="档案类型" width="120" :formatter="archiveTypeFormatter"></el-table-column>
        <el-table-column prop="securityLevel" label="保密等级" width="120" :formatter="securityLevelFormatter"></el-table-column>
        <el-table-column prop="visibleScope" label="可见范围"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" v-if="hasPermission('企业领导')">编辑</el-button>
            <el-button size="mini" type="primary" @click="downloadArchive(scope.row)" 
                       :disabled="!scope.row || !scope.row.filePath">
              <i class="el-icon-download"></i>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalArchives"
        style="margin-top: 20px;">
      </el-pagination>
    </el-card>

    <!-- Dialog for Edit Archive Security -->
    <el-dialog title="编辑档案密级与访问控制" :visible.sync="dialogVisible" width="50%">
      <el-form :model="currentArchive" label-width="120px">
        <el-form-item label="档案标题">
          <el-input v-model="currentArchive.title" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="保密等级" prop="securityLevel" :rules="[{ required: true, message: '请选择保密等级', trigger: 'change' }]">
          <el-select v-model="currentArchive.securityLevel" placeholder="请选择保密等级">
            <el-option label="绝密" value="绝密"></el-option>
            <el-option label="机密" value="机密"></el-option>
            <el-option label="秘密" value="秘密"></el-option>
            <el-option label="内部" value="内部"></el-option>
            <el-option label="公开" value="公开"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" prop="visibleScope">
          <el-input v-model="currentArchive.visibleScope" placeholder="默认为all, 可指定部门或用户ID"></el-input>
        </el-form-item>
        
        <!-- 文档内容展示 -->
        <el-form-item label="文档内容" v-if="currentArchive.ocrContent">
          <el-input
            type="textarea"
            :rows="6"
            v-model="currentArchive.ocrContent"
            :readonly="true"
            placeholder="无文档内容">
          </el-input>
        </el-form-item>
        <el-form-item label="文档内容" v-else>
          <el-alert
            title="该档案没有文档内容"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveArchiveSecurity">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';
import { downloadArchive } from '@/utils/download';

export default {
  name: 'ArchiveConfidentialityAccess',
  data() {
    return {
      archives: [],
      currentPage: 1,
      pageSize: 10,
      totalArchives: 0,
      loading: false,
      syncLoading: false,
      dialogVisible: false,
      currentArchive: {
        archiveId: null,
        title: '',
        securityLevel: '',
        visibleScope: 'all'
      },
      userRole: '',
      useElasticsearch: false,
      elasticsearchStatus: false,
      searchForm: {
        search: ''
      }
    };
  },
  created() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.role) {
      this.userRole = user.role;
    }
    this.checkElasticsearchStatus();
    this.fetchArchives();
  },
  methods: {
    hasPermission(...roles) {
      return roles.includes(this.userRole);
    },
    archiveTypeFormatter(row, column, cellValue) {
      const typeMap = {
        'Document': '文件',
        'Image': '图片',
        'Audio': '音频',
        'Video': '视频',
        'Other': '其他'
      };
      return typeMap[cellValue] || cellValue;
    },
    securityLevelFormatter(row, column, cellValue) {
      const levelMap = {
        'Confidential': '机密',
        'Secret': '秘密',
        'Internal': '内部',
        'Public': '公开'
      };
      return levelMap[cellValue] || cellValue;
    },
    fetchArchives() {
      this.loading = true;
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        search: this.searchForm.search,
        useElasticsearch: this.useElasticsearch
      };
      
      service.get('/archive/list', { params })
        .then(res => {
          if (res.data.code === 200) {
            this.archives = res.data.data.records;
            this.totalArchives = res.data.data.total;
            
            // 显示搜索结果提示
            if (this.searchForm.search && this.useElasticsearch) {
              this.$message.success(`智能搜索找到 ${this.totalArchives} 条相关档案`);
            }
          } else {
            this.$message.error(res.data.message || '获取档案列表失败');
          }
        })
        .catch(error => {
          console.error("Error fetching archives:", error);
          this.$message.error('获取档案列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleEdit(row) {
      this.currentArchive = { ...row };
      this.dialogVisible = true;
    },
    downloadArchive(archive) {
      downloadArchive(
        archive,
        (msg) => this.$message.success(msg),
        (msg) => this.$message.error(msg),
        (msg) => this.$message.warning(msg)
      );
    },
    saveArchiveSecurity() {
      service.put('/archive/update', this.currentArchive)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('档案密级与访问控制更新成功');
            this.dialogVisible = false;
            this.fetchArchives();
          } else {
            this.$message.error(res.data.message || '档案密级与访问控制更新失败');
          }
        })
        .catch(error => {
          console.error("Update archive security failed:", error);
          this.$message.error('档案密级与访问控制更新失败');
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
      this.fetchArchives();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchArchives();
    },
    handleSearch() {
      this.currentPage = 1; // 搜索时重置到第一页
      this.fetchArchives();
    },
    handleReset() {
      this.searchForm.search = '';
      this.currentPage = 1;
      this.useElasticsearch = false;
      this.fetchArchives();
    },
    handleSearchModeChange(value) {
      if (value && !this.elasticsearchStatus) {
        this.$message.warning('Elasticsearch服务不可用，无法启用智能搜索');
        this.useElasticsearch = false;
        return;
      }
      
      this.$message.info(value ? '已切换到智能搜索模式' : '已切换到普通搜索模式');
      
      // 如果有搜索内容，重新搜索
      if (this.searchForm.search) {
        this.handleSearch();
      }
    },
    checkElasticsearchStatus() {
      service.get('/archive/elasticsearch/status')
        .then(res => {
          if (res.data.code === 200) {
            this.elasticsearchStatus = res.data.data;
            if (this.elasticsearchStatus) {
              console.log('Elasticsearch服务可用');
            } else {
              console.warn('Elasticsearch服务不可用');
              this.useElasticsearch = false;
            }
          }
        })
        .catch(error => {
          console.warn('检查Elasticsearch状态失败:', error);
          this.elasticsearchStatus = false;
          this.useElasticsearch = false;
        });
    },
    syncToElasticsearch() {
      this.$confirm('确定要同步所有档案数据到Elasticsearch吗？这可能需要一些时间。', '确认同步', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.syncLoading = true;

        service.post('/archive/sync/elasticsearch')
          .then(res => {
            if (res.data.code === 200) {
              this.$message.success(`数据同步成功！共同步 ${res.data.data || 0} 条档案数据`);
              this.checkElasticsearchStatus();
            } else {
              this.$message.error('数据同步失败：' + res.data.message);
            }
          })
          .catch(error => {
            console.error('同步失败:', error);
            this.$message.error('数据同步失败');
          })
          .finally(() => {
            this.syncLoading = false;
          });
      });
    }
  }
}
</script>

<style scoped>
.archive-confidentiality-access-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.search-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.box-card .el-card__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom: none;
}

.box-card .el-card__header .clearfix span {
  font-size: 16px;
  font-weight: 500;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-pagination {
  text-align: center;
}

/* 智能搜索相关样式 */
.el-switch.is-checked .el-switch__core {
  border-color: #13ce66;
  background-color: #13ce66;
}

.el-tag {
  margin-left: 8px;
}

.el-tag--success {
  background-color: #f0f9ff;
  border-color: #13ce66;
  color: #13ce66;
}

.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #e6a23c;
  color: #e6a23c;
}

/* 加载状态 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-bottom: 10px;
  }
  
  .search-form .el-form-item__content {
    margin-left: 0 !important;
  }
}
</style> 